﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using RestSharp;

namespace ContractDemo
{
    static class HttpHelper
    {
        public static string HttpRequest(string url, Dictionary<string, string> dict, Method method)
        {
            switch (method)
            {
                case Method.GET:
                    return HttpGetRequest(url, dict);
                case Method.POST:
                    return HttpPostRequest(url, dict);
                default:
                    throw new Exception("不支持的请求方式");
            }
        }

        private static string HttpGetRequest(string url, Dictionary<string, string> dict)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(url);
            if (dict.Count > 0)
            {
                builder.Append("?");
                int i = 0;
                foreach (var item in dict)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
            }

            var request = (HttpWebRequest)WebRequest.Create(builder.ToString());
            request.Method = Method.GET.ToString();
            return GetResponse(request);
        }

        private static string HttpPostRequest(string url, Dictionary<string, string> dic)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.ContentType = "application/json";
            request.Method = Method.POST.ToString();

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                string json = JsonConvert.SerializeObject(dic);
                streamWriter.Write(json);
            }

            return GetResponse(request);
        }

        public static string HttpRequest(string url, Dictionary<string, string> postData,
            Dictionary<string, FileStream> files)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;

            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);

            //写入参数
            if (postData != null && postData.Count > 0)
            {
                var keys = postData.Keys;
                foreach (var key in keys)
                {
                    string strHeader = $"Content-Disposition: form-data; name=\"{key}\"\r\n\r\n";
                    byte[] strByte = System.Text.Encoding.UTF8.GetBytes(strHeader);
                    postStream.Write(strByte, 0, strByte.Length);


                    byte[] value = System.Text.Encoding.UTF8.GetBytes($"{postData[key]}");
                    postStream.Write(value, 0, value.Length);

                    postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                }
            }

            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);

            //写入文件
            if (files != null && files.Count > 0)
            {
                var keys = files.Keys;

                foreach (var key in keys)
                {
                    StringBuilder sbHeader = new StringBuilder(
                        $"Content-Disposition:form-data;name=\"{key}\";filename=\"{key}\"\r\nContent-Type:application/octet-stream\r\n\r\n");
                    byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());

                    FileStream fs = files[key];
                    byte[] bArr = new byte[fs.Length];
                    fs.Read(bArr, 0, bArr.Length);
                    fs.Close();
                    postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                    postStream.Write(bArr, 0, bArr.Length);

                    postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                }
            }

            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); //结束标志
            postStream.Close();
            //发送请求并获取相应回应数据
            return GetResponse(request);
        }

        private static string GetResponse(HttpWebRequest request)
        {
            string result = "";
            var response = (HttpWebResponse)request.GetResponse();
            using var streamReader = new StreamReader(response.GetResponseStream());
            result = streamReader.ReadToEnd();
            Console.WriteLine(result);
            return result;
        }
    }
}